<template>
  <view class="p-20rpx">
    <view class="rounded-16rpx bg-white px-20rpx py-30rpx">
      <view v-if="powerType === 'police'">
        <view class="label_text">网格员</view>
        <picker :range="userList" range-key="name" @change="handlePickGrider">
          <u-input
            v-model="grider"
            placeholder="请选择网格员"
            border="surround"
            readonly
            suffix-icon="arrow-down"
            suffix-icon-style="color: #999"
          ></u-input>
        </picker>
      </view>
      <view class="py-20rpx">
        <view class="label_text">
          {{ powerType === 'grider' ? '' : '下达' }}工作内容
        </view>
        <u-textarea
          v-model="content"
          placeholder="请输入工作内容"
          count
          auto-height
          adjust-position
          maxlength="200"
        ></u-textarea>
      </view>
      <view>
        <view class="label_text">
          {{ powerType === 'grider' ? '' : '下达' }}工作图片
        </view>
        <u-upload
          width="100"
          height="100"
          multiple
          :file-list="fileList"
          :max-count="9"
          @afterRead="afterRead"
          @delete="deletePic"
        ></u-upload>
      </view>
    </view>
    <view class="bottom-box">
      <u-button
        text="提交"
        color="#316ED2"
        :throttle-time="600"
        :loading="loading"
        @click="handleSubmit"
      />
    </view>
  </view>
</template>

<script lang="ts">
import dayjs from 'dayjs'
import { map } from 'lodash-es'
import { Component, Vue } from 'vue-property-decorator'

import { userStore } from '@/store'
import { showModal, showToast } from '@/utils'
@Component({ name: 'WorkReport' })
export default class WorkReport extends Vue {
  content = ''
  public fileList: Recordable[] = []
  loading = false
  grider = ''
  async handleSubmit() {
    this.loading = true
    try {
      const db = wx.cloud.database()
      if (this.powerType === 'police' && !this.grider) {
        return showToast({ title: '请选择网格员' })
      }
      if (!this.content) {
        return showToast({ title: '请输入内容' })
      }
      if (!this.fileList.length) {
        return showToast({ title: '请上传工作照片' })
      }
      if (this.powerType === 'grider') {
        /* 查询打卡记录 */
        const { data: clockInRecord } = await db
          .collection('clockInRecord')
          .where({
            name: userStore.authInfo?.name
          })
          .orderBy('time', 'desc')
          .get()
        if (!clockInRecord.length || !this.isToday(clockInRecord[0].time)) {
          await showToast({ title: '今天未打卡，请先打卡' })
          uni.redirectTo({ url: './clock-in' })
          return
        }
        const data = {
          imgList: map(this.fileList, 'url'),
          content: this.content,
          time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          name: userStore.authInfo?.name,
          address: clockInRecord[0]?.address,
          avatar: userStore.authInfo?.avatar
        }
        await db.collection('reportList').add({
          data
        })
      } else {
        const data = {
          imgList: map(this.fileList, 'url'),
          content: this.content,
          time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          name: userStore.authInfo?.name,
          avatar: userStore.authInfo?.avatar,
          grider: this.grider
        }
        await db.collection('commandList').add({
          data
        })
      }
      await showModal({ content: '提交成功' })
      uni.navigateBack({})
    } finally {
      this.loading = false
    }
  }
  handlePickGrider({ detail }: any) {
    this.grider = this.userList[+detail.value]?.name
  }
  isToday(str: string) {
    if (new Date(str).getDate() == new Date().getDate()) return true
    return false
  }

  get powerType() {
    return userStore.authInfo?.powerType
  }
  userList: any = []
  async onLoad() {
    if (userStore.authInfo?.powerType === 'police') {
      uni.setNavigationBarTitle({ title: '指令下达' })
      const db = wx.cloud.database()
      const { data: userList } = await db
        .collection('userInfo')
        .where({ powerType: 'grider' })
        .get()
      this.userList = userList
    }
  }
  deletePic(event: any) {
    this.fileList.splice(event.index, 1)
  }
  async afterRead(event: any) {
    let lists = [].concat(event.file)
    lists.map((item: any, ) => {
      this.fileList.push({
        ...item,
        status: 'uploading',
        message: '上传中'
      })
    })
    const arr = this.fileList
    for (let i = 0; i < arr.length; i++) {
      if(arr[i]?.status ==='uploading'){
        const result = await this.uploadImg(arr[i].thumb)
        let item =arr[i]
        this.fileList.splice(
          i,
          1,
          Object.assign(item, {
            status: 'success',
            message: '',
            url: result
          })
        )
      }
      
    }
  }
  async uploadImg(filePath: string) {
    const { fileID } = await wx.cloud.uploadFile({
      cloudPath: new Date().getTime().toString(),
      filePath // 文件路径
    })
    const { fileList } = await wx.cloud.getTempFileURL({
      fileList: [fileID]
    })
    return fileList[0]?.tempFileURL
  }
}
</script>

<style lang="scss" scoped>
.label_text {
  font-size: 28rpx;
  color: #666;
  margin-right: 10rpx;
  margin-bottom: 10rpx;
}
</style>
